var logger = require('pomelo-logger').getLogger('bearcat-treasures', 'Player');
var bearcat = require('bearcat');
var async = require('async');
var util = require('util');

var loginCode = function (opts) {

}

loginCode.prototype.entry = function (msg, session, next, cb) {
    var mongoDbInstance = bearcat.getBean("mongoDb");
    //是否有这个玩家
    mongoDbInstance.selectData("players", { "UnionID": msg.openid }, function (err, result) {
        console.log("mongoDbInstance = " + JSON.stringify(result));
        var count = 0;
        for (var item in result) {
            count++;
        }
        //如果没有数据库里面建立一个
        if (0 == count) {
            mongoDbInstance.getPlayerId(function (newId) {
                var param = { UnionID: msg.openid, playerid: newId, bag: [], money: 200, bindId: "", waitsendbag: [], name: "user", luck: 0, selectGroupIndex:1 };
                mongoDbInstance.insertData("players", param, function (err, res) {
                    cb(newId);
                })
            });
        }
        else {
            cb(result[0].playerid);
        }
    });
}

//得到登陆数据
loginCode.prototype.getLoginData = function (playerid, cb) {
    var mongoDbInstance = bearcat.getBean("mongoDb");
    var loginData = {};
    async.waterfall([
        function (callback) {
            mongoDbInstance.selectData("players", { playerid: playerid }, function (err, result) {
                loginData.player = result;
                callback(null);
            });
        },
        function (callback) {
            mongoDbInstance.selectData("itembox", {}, function (err, result) {
                loginData.itembox = result;
                callback(null);
            });

        },
        function (callback) {
            mongoDbInstance.selectData("baseitem", {}, function (err, result) {
                loginData.baseitem = result;
                callback(null);
            });

        }
    ],
        function (err) {
            cb(err, loginData);
        });
}

module.exports = {
    id: "loginCode",
    func: loginCode,
    init: "init",
    args: [{
        name: "opts",
        type: "Object"
    }],
    props: [{
        name: "consts",
        ref: "consts"
    }]
};

